/*
 * @Description: 博客接口
 * @version: V_00.00
 * @Company: SMD
 * @Author: Nick_Yang
 * @Date: 2018-12-12 17:16:58
 * @LastEditors: Nick_Yang
 * @LastEditTime: 2018-12-18 11:56:40
 */
let express = require('express');
let router = express.Router();
let API = require('../utils/mysql.js');
let datetime = require('silly-datetime');

router.post('/add', function (req, res, next) {
  let json = req.body || {};
  let {
    title,
    value,
    id
  } = json
  let create_time = datetime.format(new Date(), 'YYYY-MM-DD HH:mm');
  let Api = new API(req, res, next);

  if (!id) {
    Api.add('note_list', {
      title,
      create_time
    }).then(data => {
      let note_id = data.insertId

      Api.add('note_detail', {
        note_id,
        note_content: value || ''
      }).then(data => {
        res.end(JSON.stringify({
          code: 200,
          data: {
            note_id
          },
          msg: '数据添加成功'
        }))
      });
    })
    return
  }
  // 编辑
  Api.edit('note_list', {
    title,
    update_time: create_time
  }, `id = ${id}`).then(() => {
    Api.edit('note_detail', {
      note_content: value
    }, `note_id = ${id}`).then(data => {
      res.end(JSON.stringify({
        code: 200,
        data: {
          note_id: id
        },
        msg: '数据更新成功'
      }))
    })
  })
});

router.get('/getList', function (req, res, next) {
  let Api = new API(req, res, next);

  Api.get('note_list', `state = 1`).then(data => {
    res.end(JSON.stringify({
      code: 200,
      data: data
    }));
  });
});

router.get('/getDetail', function (req, res, next) {
  let Api = new API(req, res, next);
  let id = req.query.id || req.body.id || req.params.id;
  let title, note_content;
  Api.get('note_list', `id = ${id}`).then(data => {
    let obj = data[0];
    if (obj.state !== 1) {
      res.end('暂无数据');
      return
    }
    title = obj.title
    Api.get('note_detail', `note_id = ${id}`).then(data => {
      note_content = data[0].note_content;
      res.end(JSON.stringify({
        code: 200,
        data: {
          title,
          note_content
        }
      }));
    });
  });
});



module.exports = router;